<template>
  <el-drawer
      v-model="drawerOpen"
      direction="rtl"
      size="calc(100vw - 180px)"
      :with-header="false"
      :close-on-click-modal="false"
      :before-close="handleClose">
    <div style="width: 100%">
      <div style="background: #eee;padding: 10px;margin: 10px 0;" class="flex align-center justify-content-between">
        <div class="flex align-center">
          <el-button type="danger" icon="close" @click.prevent="handleClose">关闭</el-button>
          <span class="ml20">当前专题id是：{{ specialId }}，标题是：{{ specialTitle }}</span>
        </div>
      </div>
    </div>
    <el-row>
      <el-col :span="13">
        <el-tree
            style="max-width: 100%"
            :data="chapterList"
            :props="{ id: 'id',label:'title' }"
            node-key="id"
            ref="treeRef"
            default-expand-all
            @node-click="handleNodeClick"
            :expand-on-click-node="false">
          <template #default="{ node, data}">
            <div class="custom-tree-node flex justify-content-between w100 align-center">
              <span class="flex1">第{{ data.index + 1 }}{{ data.label }}：{{ node.label }}</span>
              <span>
                      <el-input v-if="data.children" size="small"
                                style="width: 110px;margin-right: 10px;text-align: center" placeholder="排序"
                                v-model="data.sorted">
                        <template #append>
                          <el-button size="small" @click="handleStatus(data,'sorted','chapter')">修改排序</el-button>
                        </template>
                      </el-input>
                      <el-input v-else size="small"
                                @blur="handleStatus(data,'sorted',(data.children?'chapter':'lesson'))"
                                style="width: 110px;margin-right: 10px;text-align: center" placeholder="排序"
                                v-model="data.sorted">
                        <template #append>
                          <el-button size="small" @click="handleUpdateSort(data,'sorted','lesson')">修改排序</el-button>
                        </template>
                      </el-input>
                    <el-button icon="plus" size="small" v-if="data.children" @click="handleOrder(node,data)" type="success">查看订单</el-button>
                    <el-button icon="plus" size="small" v-if="data.children" @click="handleCode(node,data)" type="success">生成兑换码</el-button>
                    <el-button icon="plus" size="small" v-if="data.children && data.type==1"
                               @click="handleSelect(node,data,'note')" type="success">绑定课程</el-button>
                    <el-button icon="plus" size="small" v-if="data.children && data.type==2"
                               @click="handleSelect(node,data,'download')" type="success">绑定资源</el-button>
                    <el-button icon="plus" size="small" v-if="data.children && data.type==3"
                               @click="handleSelect(node,data,'teacher')" type="success">绑定老师</el-button>
                    <el-button icon="edit" size="small" v-if="data.children"
                               @click="handleEditChapter(node,data,'chapter')" type="primary">编辑</el-button>
                    <el-button icon="close" size="small" v-if="data.children" @click="handleRemoveChapter(node,data)"
                               type="danger">删除</el-button>
                    <el-button icon="close" size="small" v-else @click="handleRemoveLesson(node,data)"
                               type="danger">删除</el-button>
                    <el-button icon="CopyDocument" size="small" v-if="data.children"
                               @click="handleCopyChapter(node,data)" type="warning">复制</el-button>
                    <el-switch
                        size="small"
                        class="ml15"
                        v-model="data.status"
                        @change="handleStatus(data, 'status',(data.children?'chapter':'lesson'))"
                        :active-value="1"
                        inline-prompt
                        active-text="已发布"
                        inactive-text="未发布"
                        :inactive-value="0"
                    ></el-switch>
                  </span>
            </div>
          </template>
        </el-tree>
      </el-col>
      <el-col :span="9">
        <el-form
            ref="formRef"
            label-width="150px"
            :model="form"
            style="padding: 30px"
            :rules="rules">
          <el-form-item label="类型选择：" required prop="type">
            <el-select v-model="form.type" class="w100" placeholder="请选择" clearable>
              <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="类型标题：" required prop="title">
            <el-input v-model="form.title" autocomplete="off" maxlength="60" placeholder="类型标题"/>
          </el-form-item>
          <el-form-item label="类型排序：" required prop="sorted">
            <el-input-number v-model="form.sorted" autocomplete="off" maxlength="10" placeholder="类型排序"/>
          </el-form-item>
          <el-form-item label="价格：" required prop="price">
            <el-input v-model="form.price" autocomplete="off" maxlength="30" placeholder="类型价格"/>
          </el-form-item>
          <el-form-item label="原价格：" required prop="realprice">
            <el-input v-model="form.realprice" autocomplete="off" maxlength="30" placeholder="类型原价格"/>
          </el-form-item>
          <el-form-item label="是否免费：" required prop="freeFlag">
            <el-radio-group v-model="form.freeFlag">
              <el-radio :label="1">收费</el-radio>
              <el-radio :label="0">免费</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否启用：" required prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :loading="suLoading" @click="handleSubmit" icon="plus">
              {{ form.id ? '更新类型' : '保存类型' }}
            </el-button>
            <el-button @click="handleReset" icon="remove">取消</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-drawer>
  <kva-select-authors ref="authorSelectRef" @select="handleSelectTeacher"></kva-select-authors>
  <kva-select-download ref="downloadSelectRef" @select="handleSelectDownload"></kva-select-download>
  <kva-select-note ref="noteSelectRef" @select="handleSelectNote"></kva-select-note>
  <bind-code ref="bindCodeRef"></bind-code>
  <bind-order ref="bindOrderRef"></bind-order>
</template>
<script setup>
import KVA from "@/utils/kva";
import {copyData, findPages, saveUpdate, removeById, updateStatus} from '@/api/special/bind.js'
import {
  saveUpdate as saveLesson,
  removeById as removeLesson,
  updateStatus as updateLessonStatus
} from '@/api/special/binddetail.js'
import debounce from '@/utils/debounce'
import KvaSelectAuthors from "@/components/kva/KvaSelectAuthors.vue";
import BindCode from "../components/BindCode.vue";
import BindOrder from "../components/BindOrder.vue";
const bindOrderRef = ref({})
const bindCodeRef = ref({})
const authorSelectRef = ref({})
const noteSelectRef = ref({})
const downloadSelectRef = ref({})
// const courseSelectRef = ref({})
const drawerOpen = ref(false)
const chapterList = ref([])
const suLoading = ref(false)
const currentNode = ref({})
const specialId = ref(0)
const bindId = ref(0)
const specialTitle = ref("")
const typeOptions = ref([
  {label: "课程", value: 1},
  {label: "资源", value: 2},
  {label: "老师", value: 3}
])

// 这个数据模型
let form = ref({})
// 表单ref, 用于提交最终得验证处理
const formRef = ref({})
const treeRef = ref({})
// 表单验证
const rules = reactive({
  title: [{required: true, message: '请输入标题', trigger: 'blur'}]
})

// 选择弹窗
const handleSelect = (node, data, type) => {
  bindId.value = data.id
  if (type == 'course') {
    courseSelectRef.value.handleOpen({})
  }
  if (type == 'note') {
    noteSelectRef.value.handleOpen({})
  }
  if (type == 'download') {
    downloadSelectRef.value.handleOpen({})
  }
  if (type == 'teacher') {
    authorSelectRef.value.handleOpen(0, {teacherFlag: 1})
  }
}


// const handleSelectCourse = async (data) => {
//   await saveLesson({courseId:data.id,specialId:specialId.value,bindId:bindId.value,type:1})
//   KVA.notifySuccess('绑定成功!')
//   handleOpen(specialId.value, specialTitle.value)
// }

const handleSelectNote = async (data) => {
  await saveLesson({noteId:data.id,specialId:specialId.value,bindId:bindId.value,type:1})
  KVA.notifySuccess('绑定成功!')
  handleOpen(specialId.value, specialTitle.value)
}

const handleSelectDownload = async (data) => {
  await saveLesson({downloadId:data.id,specialId:specialId.value,bindId:bindId.value,type:2})
  KVA.notifySuccess('绑定成功!')
  handleOpen(specialId.value, specialTitle.value)
}

const handleSelectTeacher = async(data) => {
  await saveLesson({teacherId:data.id,specialId:specialId.value,bindId:bindId.value,type:3})
  KVA.notifySuccess('绑定成功!')
  handleOpen(specialId.value, specialTitle.value)
}
// 保存和修改
const handleSubmit = () => {
  suLoading.value = true
  debounce(() => {
    formRef.value.validate(async (valid, fields) => {
      if (valid) {
        try {
          await saveUpdate(form.value)
          suLoading.value = false
          // 提示保存成功
          KVA.notifySuccess(form.value.id ? '更新成功' : '保存成功')
          // 关闭弹窗
          handleOpen(specialId.value, specialTitle.value)
          handleReset()
          form.value.specialId = specialId.value
          form.value.sorted = form.value.sorted * 1 + 1
          // 刷新方法
        } catch (ex) {
          suLoading.value = false
        }
      } else {
        suLoading.value = false

      }
    })
  }, 600)
}

const getNodeIndex = (node, index = 0) => {
  node.index = index;
  if (node.children && node.children.length == 0) {
    node.label = "类型"
    return
  }
  if (node.children && node.children.length > 0) {
    node.label = "类型"
    node.children.forEach((child, i) => {
      getNodeIndex(child, i);
    });
  } else {
    node.label = "节"
  }
}

const handleOpen = async (id, title) => {
  specialId.value = id
  specialTitle.value = title
  form.value.specialId = id
  form.value.specialTitle = title
  drawerOpen.value = true
  const resp = await findPages(id)
  form.value.sorted = resp.data.length + 1
  chapterList.value = resp.data.map((c, index) => {
    getNodeIndex(c, index)
    return c
  })
}

// 编辑类型
const handleEditChapter = (node, data) => {
  currentNode.value = node
  form.value = data
  form.value.specialTitle = specialTitle.value
}

// 删除类型
const handleRemoveChapter = (node, data) => {
  KVA.confirm('警告', '<strong>您确定要执行删除【类型】操作吗？</strong>', {icon: 'success'}).then(async () => {
    KVA.confirm('警告', '<strong>一旦执行相关的【节】全部删除！</strong>', {icon: 'success'}).then(async () => {
      await removeById(data.id)
      KVA.notifySuccess('删除成功!')
      treeRef.value.remove(node)
    })
  })
}

// 删除节
const handleRemoveLesson = (node, data) => {
  KVA.confirm('警告', '<strong>您确定要执行删除【节】操作！</strong>', {icon: 'success'}).then(async () => {
    await removeLesson(data.id)
    KVA.notifySuccess('删除成功!')
    treeRef.value.remove(node)
  })
}

// 设置收费免费
const handleStatus = async (data, field, mode) => {
  if (!data.id) return
  if (mode == "chapter") {
    await updateStatus(data.id, field, data[field])
  } else {
    await updateLessonStatus(data.id, field, data[field])
  }
  KVA.notifySuccess('操作成功!')
  handleOpen(specialId.value, specialTitle.value)
}

const handleNodeClick = (data, node) => {
  console.log(node.index);
}

// 重置
const handleReset = () => {
  form.value = {
    status:1,
    freeFlag:1,
    price:0,
    realprice:0
  }
}

const handleClose = () => {
  drawerOpen.value = false
  handleReset()
}


const handleCopyChapter = async (node, row) => {
  await copyData(row.id);
  KVA.success("复制成功!!")
  handleOpen(specialId.value, specialTitle.value)
}
// 查看订单
const handleOrder = (node,data)=>{
  bindOrderRef.value.handleOpen({specialId:specialId.value,bindId:data.id})
}

// 查看兑换码
const handleCode = (node,data)=>{
  bindCodeRef.value.handleOpen({specialId:specialId.value,bindId:data.id})
}


defineExpose({
  handleOpen,
  handleClose
})
</script>
<style>
.el-tree-node__content {
  padding: 1px 0 !important;
}

.el-tree-node__children {
  margin-left: 15px;
}
</style>